package com.toidep.fragment.mains;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import com.toidep.R;
import com.toidep.activities.MainActivity;
import com.toidep.activities.RegisterActivity;
import com.toidep.adapters.EmailAdapter;
import com.toidep.api.ApiController;
import com.toidep.api.ParseJSON;
import com.toidep.base.BaseFragment;
import com.toidep.config.ConfigUtility;
import com.toidep.config.Constants;
import com.toidep.entities.CityEntity;
import com.toidep.interfaces.ConfirmChangePassListener;
import com.toidep.interfaces.ResponseListener;
import com.toidep.payment.PaymentControl;
import com.toidep.preference.SharePreference;
import com.toidep.utilities.DialogUtility;
import com.toidep.widgets.sectionlist.AmazingListView;

public class UserInfoFragment extends BaseFragment implements OnClickListener {

	public boolean isRootFragment = true;
	
	private View view;

	private MainActivity mainActivity;
	
	private RelativeLayout layoutButtonUserInfo,layoutButtonEditInfo, layoutButtonMessageInfo, layoutButtonTransactionHistory; 
	private RelativeLayout layoutUserInfo, layoutEditInfo, layoutMessageInfo, layoutTransactionHistory;
	// Tab UserInfo
	private TextView username, userAccount, userBirthday, userGender, userEmail, userProvice, userPhone;
	// Tab EditInfo
	private TextView textviewAccount, textviewPhone;
	private EditText edittextChangeEmail, edittextChangeFullName, edittextBirthday;
	private Spinner cbTowns;
	private RadioButton radioMale, radioFemale;
	private Button buttonChangePassword, buttonUpdateUserInfo;
	private TextView textviewButtonChangePhone;
	
	private int year;
	private int month;
	private int day;
	
	// Tab Email
	private AmazingListView emailListView;
	private EmailAdapter emailAdapter;
	// Tab History
	private TextView /*textPhone, textPoint, buttonRegCharge, */textUserInfo, textHistory;
	
	/**
	 * Set lai cac base value cho fragment: cac item cua thanh header, currentCategory cua menuSideBar
	 */
	public void setBaseValues() {
		mainActivity.currentCategory = Constants.CATEGORY_USER_INFO;
		mainActivity.mainFragment.setTittle(mainActivity.getString(R.string.label_category_user_info));
		mainActivity.mainFragment.showButtonSlide(true);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		view = inflater.inflate(R.layout.fragment_user_info, container, false);

		mainActivity = (MainActivity) getActivity();

		initComponents();
		
		getAllInforUser(true);
		
		setBaseValues();
		
		return view;
	}

	private void initComponents() {
		layoutButtonUserInfo = (RelativeLayout) view.findViewById(R.id.layoutButtonUserInfo);
		layoutButtonEditInfo = (RelativeLayout) view.findViewById(R.id.layoutButtonEditInfo);
		layoutButtonMessageInfo = (RelativeLayout) view.findViewById(R.id.layoutButtonMessage);
		layoutButtonTransactionHistory = (RelativeLayout) view.findViewById(R.id.layoutButtonTransactionHistory);
		
		layoutUserInfo = (RelativeLayout) view.findViewById(R.id.layoutUserInfo);
		layoutEditInfo = (RelativeLayout) view.findViewById(R.id.layoutEditInfo);
		layoutMessageInfo = (RelativeLayout) view.findViewById(R.id.layoutMessageInfo);
		layoutTransactionHistory = (RelativeLayout) view.findViewById(R.id.layoutTransactionHistory);

		layoutButtonUserInfo.setOnClickListener(this);
		layoutButtonEditInfo.setOnClickListener(this);
		layoutButtonMessageInfo.setOnClickListener(this);
		layoutButtonTransactionHistory.setOnClickListener(this);
		
		// Tab UserInfor 
		username		= (TextView) view.findViewById(R.id.username);
		userAccount		= (TextView) view.findViewById(R.id.userAccount);
		userBirthday	= (TextView) view.findViewById(R.id.userBirthday);
		userGender			= (TextView) view.findViewById(R.id.userSex);
		userProvice		= (TextView) view.findViewById(R.id.userProvice);
		userEmail		= (TextView) view.findViewById(R.id.userEmail);
		userPhone		= (TextView) view.findViewById(R.id.userPhone);
		
		// Tab Edit Info
		textviewAccount = (TextView) view.findViewById(R.id.textviewAccount);
		textviewPhone = (TextView) view.findViewById(R.id.textviewPhone);
		
		textviewButtonChangePhone = (TextView) view.findViewById(R.id.textviewButtonChangePhone);
		textviewButtonChangePhone.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				changePhone();
			}
		});
		
		edittextChangeEmail = (EditText) view.findViewById(R.id.edittextChangeEmail);
		edittextChangeFullName = (EditText) view.findViewById(R.id.edittextChangeFullName);
		
		cbTowns = (Spinner) view.findViewById(R.id.spTowns);
		
		radioMale = (RadioButton) view.findViewById(R.id.radioMale); 
		radioFemale = (RadioButton) view.findViewById(R.id.radioFemale); 

		edittextBirthday = (EditText) view.findViewById(R.id.edittextChangeBirthday);
		edittextBirthday.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				setCurrentDateOnView();
				DatePickerDialog dialog = new DatePickerDialog(
						getActivity(), 
						datePickerListener, 
						year, 
						month, 
						day);
				dialog.getDatePicker().setMaxDate(Calendar.getInstance().getTimeInMillis());
				dialog.show();
			}
		});
		edittextBirthday.setInputType( InputType.TYPE_NULL );
		
		buttonUpdateUserInfo = (Button) view.findViewById(R.id.buttonUpdateUserInfo);
		buttonUpdateUserInfo.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				updateUserInfo();
			}
		});
		
		buttonChangePassword = (Button) view.findViewById(R.id.buttonChangePassword);
		buttonChangePassword.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				mainActivity.showProgressDialog();
				DialogUtility.showDialogChangePassword(
						getActivity(), 
						"", 
						"",
						new ConfirmChangePassListener() {
							
							@Override
							public void doCancel() {
								mainActivity.closeProgressDialog();
							}
							
							@Override
							public void doAccept(String oldPass, String newPass, String newPassAgain) {
								doChangePass(oldPass, newPass, newPassAgain);

								mainActivity.closeProgressDialog();
							}
						});
			}
		});
		// Tab Email
		emailListView = (AmazingListView) view.findViewById(R.id.emailListView);
		emailListView.setLoadingView(getActivity().getLayoutInflater().inflate(R.layout.layout_loading_view, null));
		
		// Tab Histoty
		textUserInfo = (TextView) view.findViewById(R.id.textUserInfo);
		textHistory = (TextView) view.findViewById(R.id.textHistory);
	}

	public static UserInfoFragment newInstance() {
		UserInfoFragment myFragment = new UserInfoFragment();

		myFragment.setRootFragment(true);
		return myFragment;
	}
	
	private void switchTab(int tabMode) {
		switch (tabMode) {
		case Constants.TAB_MODE_USER_INFO:
			// Menu color
			layoutButtonUserInfo.setBackgroundResource(R.drawable.bg_red_normal);
			layoutButtonEditInfo.setBackgroundResource(R.drawable.bg_horizontal_button_menu);
			layoutButtonMessageInfo.setBackgroundResource(R.drawable.bg_horizontal_button_menu);
			layoutButtonTransactionHistory.setBackgroundResource(R.drawable.bg_horizontal_button_menu);
						
			// Layout content
			layoutUserInfo.setVisibility(View.VISIBLE);
			layoutEditInfo.setVisibility(View.GONE);
			layoutMessageInfo.setVisibility(View.GONE);
			layoutTransactionHistory.setVisibility(View.GONE);
			
			// Request data (if needed)
			requestData(Constants.TAB_MODE_USER_INFO);
			break;
		case Constants.TAB_MODE_USER_HISTORY:
			// Menu color
			layoutButtonUserInfo.setBackgroundResource(R.drawable.bg_horizontal_button_menu);
			layoutButtonEditInfo.setBackgroundResource(R.drawable.bg_horizontal_button_menu);
			layoutButtonMessageInfo.setBackgroundResource(R.drawable.bg_horizontal_button_menu);
			layoutButtonTransactionHistory.setBackgroundResource(R.drawable.bg_red_normal);
						
			// Layout content
			layoutUserInfo.setVisibility(View.GONE);
			layoutEditInfo.setVisibility(View.GONE);
			layoutMessageInfo.setVisibility(View.GONE);
			layoutTransactionHistory.setVisibility(View.VISIBLE);
			
			// Request data (if needed)
			requestData(Constants.TAB_MODE_USER_HISTORY);
			break;
		case Constants.TAB_MODE_EDIT_INFO:
			// Menu color
			layoutButtonUserInfo.setBackgroundResource(R.drawable.bg_horizontal_button_menu);
			layoutButtonEditInfo.setBackgroundResource(R.drawable.bg_red_normal);
			layoutButtonMessageInfo.setBackgroundResource(R.drawable.bg_horizontal_button_menu);
			layoutButtonTransactionHistory.setBackgroundResource(R.drawable.bg_horizontal_button_menu);
						
			// Layout content
			layoutUserInfo.setVisibility(View.GONE);
			layoutEditInfo.setVisibility(View.VISIBLE);
			layoutMessageInfo.setVisibility(View.GONE);
			layoutTransactionHistory.setVisibility(View.GONE);
			
			// Request data (if needed)
			requestData(Constants.TAB_MODE_EDIT_INFO);
			break;
		case Constants.TAB_MODE_MESSAGE_INFO:
			// Menu color
			layoutButtonUserInfo.setBackgroundResource(R.drawable.bg_horizontal_button_menu);
			layoutButtonEditInfo.setBackgroundResource(R.drawable.bg_horizontal_button_menu);
			layoutButtonMessageInfo.setBackgroundResource(R.drawable.bg_red_normal);
			layoutButtonTransactionHistory.setBackgroundResource(R.drawable.bg_horizontal_button_menu);
						
			// Layout content
			layoutUserInfo.setVisibility(View.GONE);
			layoutEditInfo.setVisibility(View.GONE);
			layoutMessageInfo.setVisibility(View.VISIBLE);
			layoutTransactionHistory.setVisibility(View.GONE);
			
			// Request data (if needed)
			requestData(Constants.TAB_MODE_MESSAGE_INFO);
			break;
		}
	}
	
	private void requestData(int tabMode) {
		switch (tabMode) {
		case Constants.TAB_MODE_USER_INFO:
			setWidgetsUserInfoTab();
			break;
		case Constants.TAB_MODE_EDIT_INFO:
			setWidgetsEditInfoTab();
			break;
		case Constants.TAB_MODE_MESSAGE_INFO:
			emailListView.setAdapter(emailAdapter = new EmailAdapter(this));
			emailAdapter.setAmazingListView(emailListView, ConfigUtility.PAGE_SIZE);
			emailListView.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
					if (emailAdapter != null && position >= 0) {
						emailAdapter.onItemClick(position);
					}
				}
			});
			emailAdapter.resetList();
			break;
		case Constants.TAB_MODE_USER_HISTORY:
			setWidgetsHistoryTab();
			break;
		}
	}
	
	private void getAllInforUser(final boolean isSwitchTab) {
		ApiController.getAllInforUser(mainActivity, new ResponseListener() {
			
			@Override
			public void processResponse(int inintstall) {
				switchTab(Constants.TAB_MODE_USER_INFO);
			}
			
			@Override
			public void processResponse(String response) {
				try {
					JSONObject jsonObject = new JSONObject(response);
					int code = ParseJSON.getIntValue(jsonObject, Constants.PARAM_RESPONSE_CODE);
					if(code == 0){
						if(mainActivity instanceof MainActivity){
							MainActivity main = (MainActivity) mainActivity;
							main.login();
						}
					}else{
//					ParseJSON.getVideoDetailObjectFromResponse(response);
						ParseJSON.getUserAllInfoFromResponse(mainActivity, response);
						if (isSwitchTab) {
							switchTab(Constants.TAB_MODE_USER_INFO);
						}
					}
				} catch (Exception e) {
				}
				
			}
		});
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.layoutButtonUserInfo:
			switchTab(Constants.TAB_MODE_USER_INFO);
			break;
		case R.id.layoutButtonEditInfo:
			switchTab(Constants.TAB_MODE_EDIT_INFO);
			break;
		case R.id.layoutButtonMessage:
			switchTab(Constants.TAB_MODE_MESSAGE_INFO);
			break;
		case R.id.layoutButtonTransactionHistory:
			switchTab(Constants.TAB_MODE_USER_HISTORY);
			break;
		}
	}

	/*
	 * User Info actions
	 */
	private void setWidgetsUserInfoTab() {
		SharePreference sharePreference = SharePreference.getInstance(mainActivity);
		boolean loginStatus = sharePreference.getLoginStatus();
		if (loginStatus) {
			username.setText(sharePreference.getUserFullName());
			userAccount.setText(sharePreference.getUserName());
			userEmail.setText(sharePreference.getUserEmail());
			userPhone.setText(sharePreference.getUserPhone());
			userBirthday.setText(sharePreference.getUserBirthday());
			userProvice.setText(sharePreference.getUserProvince());
			int gender = sharePreference.getUserGender();
			if (gender == 1) {
				userGender.setText(mainActivity
						.getString(R.string.label_user_info_sex_male));
			} else if (gender == 2) {
				userGender.setText(mainActivity
						.getString(R.string.label_user_info_sex_female));
			}else{
				userGender.setText("");
			}
		}
	}
	
	ArrayList<CityEntity> cityList;
	/*
	 * Edit Info actions
	 */
	private void setWidgetsEditInfoTab() {
		final SharePreference sharePreference = SharePreference.getInstance(mainActivity);
		boolean loginStatus = sharePreference.getLoginStatus();
		if (loginStatus) {
			textviewAccount.setText(sharePreference.getUserName());
			textviewPhone.setText(sharePreference.getUserPhone());
			edittextChangeEmail.setText(sharePreference.getUserEmail());
			edittextChangeFullName.setText(sharePreference.getUserFullName());
			boolean isMale = sharePreference.getUserGender() == 1;
			radioMale.setChecked(isMale);
			radioFemale.setChecked(!isMale);
			edittextBirthday.setText(sharePreference.getUserBirthday());
			ApiController.getCityData(mainActivity, new ResponseListener() {
				
				@Override
				public void processResponse(int inintstall) {
					
				}
				
				@Override
				public void processResponse(String response) {
					cityList =ParseJSON.getCityObjectFromResponse(response);
					if (cityList == null) return;
					
					ArrayAdapter<CityEntity> dataAdapter = new ArrayAdapter<CityEntity>(mainActivity, android.R.layout.simple_spinner_item,cityList);
					dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					cbTowns.setAdapter(dataAdapter);
					int crrIndex = 0;
					int index = 0;
					for (CityEntity item : cityList) {
						
						if (item.getName().equals(sharePreference.getUserProvince())) {
							index = crrIndex;
							break;
						}
						crrIndex++;	
					}
					cbTowns.setSelection(index);
				}
			});
			
			
			
		}
	}
	
	private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

		// when dialog box is closed, below method will be called.
		public void onDateSet(DatePicker view, int selectedYear,
				int selectedMonth, int selectedDay) {
			year = selectedYear;
			month = selectedMonth;
			day = selectedDay;

			// set selected date into textview
			edittextBirthday.setText(new StringBuilder().append(day)
					.append("-").append(month + 1).append("-").append(year));

		}
	};
	
	// display current date
	public void setCurrentDateOnView() {
 
		final Calendar c = Calendar.getInstance();
		year = c.get(Calendar.YEAR);
		month = c.get(Calendar.MONTH);
		day = c.get(Calendar.DAY_OF_MONTH);
 
	}

	public boolean isValidDate(String dateString) {
	    SimpleDateFormat df = new SimpleDateFormat("MM-dd-yyyy");
	    try {
	        df.parse(dateString);
	        return true;
	    } catch (ParseException e) {
	        return false;
	    }
	}
	
	private boolean isValidEmail(String target) {
		  if (TextUtils.isEmpty(target)) {
		    return false;
		  } else {
		    return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
		  }
		}
	
	private void updateUserInfo() {
		final String newEmail = edittextChangeEmail.getText().toString();
		if(!isValidEmail(newEmail)){
			DialogUtility.showDialogAlert(
					getActivity(), 
					"", 
					"Bạn đã nhập email sai định dạng", 
					getString(R.string.label_close), 
					null);
			return;
		}
		
		final String newFullName = edittextChangeFullName.getText().toString();
		final String newBirthday = edittextBirthday.getText().toString();
		final int newGender = radioMale.isChecked() ? 1 : 2;
		final String cityId = ((CityEntity)cbTowns.getSelectedItem()).getId();
//		if(!isValidDate(newBirthday)) {
//			DialogUtility.showDialogAlert(getActivity(), "", "Ngày sinh không hợp lệ","OK", null);
//		}
		ApiController.editProfile (
				mainActivity, 
				newEmail, 
				newFullName, 
				newBirthday, 
				newGender,
				cityId,
				new ResponseListener() {
					
					@Override
					public void processResponse(int inintstall) {
						// TODO Auto-generated method stub
						
					}
					
					@Override
					public void processResponse(String response) {
						// Bug #308 - start
						JSONObject obj;
						try {
							obj = new JSONObject(response);
							String text = ParseJSON.getStringValue(obj, Constants.PARAM_RESPONSE_MESSAGE);
//							Log.e("editProfile response", response + "||" + text);
							if (!text.equals("")) {
								DialogUtility.showDialogAlert(getActivity(), "", text, "OK", null);
							}
							
							int code = ParseJSON.getIntValue(obj, Constants.PARAM_REQUEST_CODE);
							if (code == 1) {
						    	getAllInforUser(false);
						    }
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
						// Bug #308 - end
						
					}
				});			
	}
	
	private void changePhone() {
		PaymentControl paymentControl = new PaymentControl(mainActivity);
		paymentControl.setTitle("Đổi Số điện thoại");
		paymentControl.setListener(new ResponseListener() {
			
			@Override
			public void processResponse(int inintstall) {
				if (inintstall == 1) {
					String newPhone = SharePreference.getInstance(mainActivity).getUserPhone();
					textviewPhone.setText(newPhone);
				}
			}
			
			@Override
			public void processResponse(String response) {
				// TODO Auto-generated method stub
			}
		});
		paymentControl.doPaymentBySub();
	}
	
	
	private void doChangePass(String oldPass, String newPass, String newPassAgain) {
		
	}
	
	/*
	 * History Info actions
	 */
	private void setWidgetsHistoryTab() {
		ApiController.getPointUser(mainActivity, new ResponseListener() {
			
			@Override
			public void processResponse(int inintstall) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void processResponse(String response) {
				String text = ParseJSON.getTextDataFromResponse(response);
				textUserInfo.setText(text);
				
				ApiController.getHistory(mainActivity, new ResponseListener() {
					
					@Override
					public void processResponse(int inintstall) {
						// TODO Auto-generated method stub
						
					}
					
					@Override
					public void processResponse(String response) {
						String text = ParseJSON.getTextDataFromResponse(response);
						textHistory.setText(text);
					}
				});
			}
		});
		
//		SharePreference sharePreference = SharePreference.getInstance(mainActivity);
//		boolean loginStatus = sharePreference.getLoginStatus();
//		if (loginStatus) {
//			textPhone.setText(sharePreference.getUserPhone());
//			textPoint.setText(sharePreference.getUserPoint());
//			textHistory.setText(sharePreference.getUserPoint());
//			
//			buttonRegCharge.setOnClickListener(new OnClickListener() {
//				
//				@Override
//				public void onClick(View v) {
//					(new PaymentControl(mainActivity)).startPayment(null);
//				}
//			});
//		}
	}
}
